import java.util.*;

/**
 * Created by L.jp
 * Description:已知有几笔金额不等的钱和几个笔待支付的订单。请将钱分配至这些订单，记录分配关系，如不够，分配完
 为止，如有多余，记录剩余金额的构成。以下金额统一为CNY，单位元。
 要求输出：
 1、分配关系
 2、剩余金额构成
 举例：
 金钱：A： 100, B：66, C：99, D: 109
 订单：X：34, Y：90， Z：118
 输出：
 分配结果：{X=[{A=34}], Y=[{A=66}, {B=24}], Z=[{B=42}, {C=76}]}
 剩余金额：{A=0,B=0,C=23,D=109}
 
 *User: 86189
 * Date: 2023-05-10
 * Time: 23:44
 */
public class Main {
        public static void main(String[] args) {
            Map<String, Integer> money = new HashMap<>();
            money.put("A", 100);
            money.put("B", 66);
            money.put("C", 99);
            money.put("D", 109);
    
            Map<String, Integer> orders = new HashMap<>();
            orders.put("X", 34);
            orders.put("Y", 90);
            orders.put("Z", 118);
    
            Map<String, List<Map<String, Integer>>> allocation = new HashMap<>();
            Map<String, Integer> remaining = new HashMap<>();
    
            for (Map.Entry<String, Integer> order : orders.entrySet()) {
                String orderId = order.getKey();
                int orderAmount = order.getValue();
                List<Map<String, Integer>> assignedMoney = new ArrayList<>();
        
                for (Map.Entry<String, Integer> m : money.entrySet()) {
                    String moneyId = m.getKey();
                    int moneyAmount = m.getValue();
            
                    if (moneyAmount >= orderAmount) {
                        assignedMoney.add(Collections.singletonMap(moneyId, orderAmount));
                        money.put(moneyId, moneyAmount - orderAmount);
                        break;
                    } else {
                        assignedMoney.add(Collections.singletonMap(moneyId, moneyAmount));
                        money.put(moneyId, 0);
                        orderAmount -= moneyAmount;
                    }
                }
        
                allocation.put(orderId, assignedMoney);
            }
    
            for (Map.Entry<String, Integer> m : money.entrySet()) {
                String moneyId = m.getKey();
                int moneyAmount = m.getValue();
                if (moneyAmount > 0) {
                    remaining.put(moneyId, moneyAmount);
                }
            }
    
            System.out.println("分配结果：" + allocation);
            System.out.println("剩余金额：" + remaining);
        }

}
